package 力扣日常刷题.木23一月.第02天302;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 帅小伙
 * @date 2022/3/2
 * @description
 */
public class Demo22三数之和 {

    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        ArrayList<List<Integer>> ans = new ArrayList<List<Integer>>();
        if (n < 3 || nums[0] > 0) return ans;

        for (int i = 0; i < nums.length; i++) {
            int l = i + 1, r = nums.length - 1;
            while(l < r) {
                if (nums[i] + nums[l] + nums[r] > 0) r--;
                else if (nums[i] + nums[l] + nums[r] < 0) l++;
                else {
                    ArrayList<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[l]);
                    list.add(nums[r]);
                    ans.add(list);
                    while (l < r && nums[l] == nums[l + 1]) l++;
                    while (l < r && nums[r] == nums[r - 1]) r--;
                    l++;
                    r--;
                }
            }

            while(i+1 < n && nums[i] == nums[i+1]) i++;
        }
        return ans;
    }

}
